package config

import (
	"sync"
	"time"
)

type CommonService struct {
	done, close chan struct{}
	run         sync.Once
}

//后台执行知道收到退出信号
func (cs *CommonService) Start(fn func() time.Duration) {
	go func() {
		cs.run.Do(
			func() {
				for {
					select {
					case <-time.After(fn()):
						continue
					case <-cs.close:
						close(cs.done)
						return
					}
				}
			})
	}()
}

func (cs *CommonService) Close() {
	close(cs.close)
	<-cs.done
}

func NewCommonService() *CommonService {
	return &CommonService{done: make(chan struct{}, 0), close: make(chan struct{}, 0)}
}
